<template>
  <div>
    <el-card :body-style="{ padding: '20px' }">
      <template v-slot:header>
        <el-button type="primary" icon="ele-Plus" @click="addDialog">添加</el-button>
      </template>

      <!-- table在动态展示数据的时候
      data:我们一旦把数据给了,会自动把这个数组给到每个列
      每个列的内部都是在遍历这个数组,我们就可以通过列上的属性
      prop来规定这个列遍历的时候显示对象的哪个属性.
      但是如果要显示的数据需要额外的结构,那么每个列内部也给你提供了作用域插槽,我们就要使用作用域插槽
      给数据添加额外的结构和样式
    -->
      <el-table :data="trademarkList" border stripe>
        <!-- v-for="col in columns" :prop="col.id" :key="col.id" -->
        <el-table-column label="序号" :width="80" align="center" type="index"></el-table-column>
        <el-table-column label="品牌名称" prop="tmName"></el-table-column>
        <el-table-column label="平牌LOGO">
          <template v-slot="{row,$index}">
            <el-image :src="row.logoUrl" style="width: 100px;height: 60px;"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template v-slot="{row,$index}">
            <el-button type="warning" size="small" icon="ele-Edit" @click="changeDialog(row)">修改</el-button>
            <el-button type="danger" size="small" icon="ele-Delete" @click="">删除</el-button>
            <el-button type="danger" size="small" icon="ele-Delete" @click="open(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 
        点击能发送请求切换页码，不再是静态变化，而是发送真实请求在变化
        @size-change="handleSizeChange"
        点击能发送请求跳转到该页，不再是静态变化，而是发送真实请求在变化  ？？？
      @current-change="handleCurrentChange" -->
      <el-pagination style="margin-top: 20px;" v-model:current-page="page" v-model:page-size="limit"
        :page-sizes="[3, 5, 7, 10]" layout="prev, pager, next, jumper,->,sizes, total" :total="total"
        @size-change="handleSizeChange" @current-change="getTrademarkList"></el-pagination>

      <!-- 对话框dialog-->
      <!-- Form -->
      <el-dialog v-model="isShowDialog" :title="tmForm.id ? '修改品牌' : '添加品牌'">
        <el-form style="width: 80%;">
          <el-form-item label="品牌名称" label-width="100px">
            <el-input autocomplete="off" v-model="tmForm.tmName" />
          </el-form-item>
          <el-form-item label="品牌LOGO" label-width="100px">
            <!-- 上传图片后，前端将图片信息传给后端，后端返回前端图片地址，而action=""放的是后端传过来图片的地址  写:是props @是事件-->
            <el-upload class="avatar-uploader" action="/app-dev/admin/product/fileUpload" :show-file-list="false"
              :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
              <img v-if="tmForm.logoUrl" :src="tmForm.logoUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
              <!-- 图片下面一行字 -->
              <template #tip>
                <div class="el-upload__tip">
                  上传的图片必须是jpg且不能大于2M
                </div>
              </template>
            </el-upload>

          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="isShowDialog=false">取消</el-button>
            <el-button type="primary" @click="addOrChangeTrademark">
              确认
            </el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script lang="ts">
import { defineComponent } from "vue";

export default defineComponent({
  name: "Trademark",
});
</script>



<script setup lang="ts">
import { ref, onMounted } from "vue";
import trademarkApi from "@/api/trademark";
import type { TrademarkData } from "@/api/trademark";
import { ElMessage } from "element-plus";
import { markRaw } from "vue";
import { Delete } from "@element-plus/icons-vue";
import { ElMessageBox } from "element-plus";

// 图片copy-------------------------------------------
// import { ref } from 'vue'
// import { ElMessage } from 'element-plus'
import { Plus } from "@element-plus/icons-vue";
import type { UploadProps } from "element-plus";

const imageUrl = ref("");
// 添加逻辑
// 弹出对话框需要我们收集用户输入的数据
// 1\收集什么    看接口文档的参数
// {
//   tmName
//   logoUrl
// }
// 2\收集带哪    自己定义
const tmForm = ref<TrademarkData>({
  tmName: "",
  logoUrl: "",
});
// 上传成功的回调拿到的是response
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!)  //该地址为本地地址，我们不要
  // console.log(imageUrl.value);
  // console.log(response, uploadFile);  打印结构里都有data：图片地址，选择response取值
  // 将 response.data赋值给tmForm.value.logoUrl，就能拿到图片了
  tmForm.value.logoUrl = response.data;
};
// 上传校验，我们把这里提示的英文换成中文
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("上传的图片格式必须为image/jpeg!");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("上传图片不得超过2MB!");
    return false;
  }
  return true;
};
//data-----------------------------------------------------
// 分页需要的数据
const page = ref(1);
const limit = ref(3);
const total = ref(0);
const trademarkList = ref<TrademarkData[]>([]);

//封装发请求获取分页列表函数
const getTrademarkList = async (pager = 1) => {
  page.value = pager;
  try {
    const result = await trademarkApi.getPageList(page.value, limit.value);
    // console.log(result);  一定要检查数据是否拿到！！！
    trademarkList.value = result.records;
    total.value = result.total;
    return "ok";
  } catch (error) {
    ElMessage.error("获取品牌列表失败");
    return Promise.reject(error);
  }
};

const handleSizeChange = (size: number) => {
  limit.value = size;
  getTrademarkList();
};

onMounted(() => {
  getTrademarkList();
});

//dialog对话框-------------------------------------------------------
//点击添加按钮显示dialog对话框，添加不需要回显数据
const isShowDialog = ref(false);
const addDialog = () => {
  isShowDialog.value = true;
  tmForm.value = {
    tmName: "",
    logoUrl: "",
  };
};
// --------------------------------------------------------
//修改按钮显示dialog对话框，但是修改是需要回显数据的
const changeDialog = (row: TrademarkData) => {
  isShowDialog.value = true;
  tmForm.value = { ...row };
};
// ---------------------------------------
// 封装点击确定（添加或者修改对话框里的）发请求函数
const addOrChangeTrademark = async () => {
  // 公式：
  // 获取收集数据
  let trademark = tmForm.value;
  // 整理数据（是否合格） 这里合适不需要整理
  // 发请求
  try {
    // 成功后作甚
    await trademarkApi.addOrUpdate(trademark);
    ElMessage.success(trademark.id ? "修改品牌成功" : "添加品牌成功");
    isShowDialog.value = false;
  } catch (error) {
    // 失败了作甚
    ElMessage.error(trademark.id ? "修改品牌成功" : "添加品牌成功");
  }
};
// -------------------------------------------
// 点击删除
const open = (row: TrademarkData) => {
  ElMessageBox.confirm(`你确定要删除${row.tmName}吗？`, "Warning", {
    type: "warning",
    icon: markRaw(Delete),
  })
    .then(async () => {
      try {
        await trademarkApi.delete(row.id as number);
        ElMessage.success("删除该品牌已成功！");
        getTrademarkList(
          trademarkList.value.length > 1 ? page.value : page.value - 1
        );
      } catch (error) {
        ElMessage.error("删除品牌失败" + (error as Error).message);
      }
    })
    .catch(() => {
      ElMessage.warning("取消删除");
    });
};
</script>


<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>


<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>

